package com.db.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public final class WorkerThread implements Runnable {

	Socket connection;

	public WorkerThread(Socket socket) {
		this.connection = socket;
	}

	public static void startPool(int suggestedPort) throws IOException {
		Parameter.setPort(suggestedPort);
		Parameter.print();
		int port = Parameter.getPort();
		int workers = Parameter.getWorkers();
		int timeout = Parameter.getTimeout();

		// create server socket
		ServerSocket serversocket = new ServerSocket(port);

		// create pool of worker threads
		Executor executor = Executors.newFixedThreadPool(workers);

		while (!Thread.currentThread().isInterrupted()) {
			// accept connections
			Socket newConnection = serversocket.accept();
			newConnection.setSoTimeout(timeout);
			executor.execute(new WorkerThread(newConnection));
		}
		serversocket.close();
	}

	public void run() {

		try {
			new Worker().handleRequest(connection);
		} catch (SocketTimeoutException e) {
			Parameter.getLog().println("ERROR SocketTimeoutException " );
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}